package com.example.image.glidemodule

import android.content.Context
import android.os.Environment
import com.bumptech.glide.Glide
import com.bumptech.glide.Registry
import com.bumptech.glide.annotation.GlideModule
import com.bumptech.glide.integration.okhttp3.OkHttpUrlLoader
import com.bumptech.glide.load.model.GlideUrl
import com.bumptech.glide.module.LibraryGlideModule
import okhttp3.Cache
import okhttp3.OkHttpClient
import java.io.File
import java.io.InputStream

/**
 * 使用OkHttpClient设置网络缓存大小
 */
@GlideModule
class OkHttpModule : LibraryGlideModule(){
    override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
        //创建一个OKHttpClient的builder
        val builder = OkHttpClient.Builder()
        //外部SDK的目录
        val externalDir =Environment.getExternalStorageDirectory()
        if(externalDir.exists()){
            val cacheDir = "${externalDir.absolutePath}/cacheImages"
            var cacheFile = File(cacheDir)
            if(!cacheFile.exists()){
                cacheFile = File(cacheDir)
            }
            val cache = Cache(cacheFile,1024*1024*250L)
            builder.cache(cache)
        }else{
            val cacheDir = "${context.externalCacheDir?.absolutePath}/cacheImages"
            var cacheFile = File(cacheDir)
            if(!cacheFile.exists()){
                cacheFile = File(cacheDir)
            }
            var cacheSize = 50*1024*1024L
            context.externalCacheDir?.totalSpace?.let {
                cacheSize = it / 8
            }
            val cache = Cache(cacheFile,cacheSize)
            builder.cache(cache)
        }
        //替换OKHttpClient对象
        val newOkHttpClient = builder.build()
        registry.replace(GlideUrl::class.java, InputStream::class.java, OkHttpUrlLoader.Factory(newOkHttpClient))
    }
}